package com.lightsh.network;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Locale;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.os.StatFs;
import android.util.Base64;



public class Utility {
	
	private static final boolean DEBUG = true;
	
	private static final int WAP_CONNECT_TIME_OUT = 60 * 1000;
	private static final int WAP_READ_TIME_OUT = 60 * 1000;
	
	private static final int NORMAL_CONNECT_TIME_OUT = 30 * 1000;
	private static final int NORMAL_READ_TIME_OUT = 30 * 1000;
	
    // 获取链接
    public final static HttpURLConnection getConnection(String url) throws IOException {
        HttpURLConnection con = null;        
        if (mNetworkProxyHost != null && !mNetworkProxyHost.equals("")) {
        	// 使用cmwap
        	String signFirst = "://";
        	String signSlash = "/";
        	int nPosFirst = url.indexOf(signFirst) + signFirst.length();			//< host的开始位置
        	int nPosSecond = url.indexOf(signSlash, nPosFirst);						//< host后面的"/"位置
        	String host = url.substring(nPosFirst, nPosSecond);
        	
        	String strUrl = url.substring(0, nPosFirst) + mNetworkProxyHost;
        	strUrl += url.substring(nPosSecond);
        	
        	URL proxyUrl = new URL(strUrl);  
        	con = (HttpURLConnection) proxyUrl.openConnection();  
        	con.setRequestProperty("X-Online-Host", host);
        	
        	con.setConnectTimeout(WAP_CONNECT_TIME_OUT);
            con.setReadTimeout(WAP_READ_TIME_OUT);
        	
        } else {
            con = (HttpURLConnection) new URL(url).openConnection();
            con.setConnectTimeout(NORMAL_CONNECT_TIME_OUT);
            con.setReadTimeout(NORMAL_READ_TIME_OUT);
        }
        // 加入语言
        con.setRequestProperty("Accept-Language", Locale.getDefault().getLanguage().toLowerCase() + "-" + Locale.getDefault().getCountry().toLowerCase());
            
        return con;
    }
    
    // 将资源图片转成可网络传输的byte[],即做base64编码
    public static byte[] resourceToBytes(Resources res, int bitmapId){
    	Bitmap bmp = BitmapFactory.decodeResource(res, bitmapId);
    	ByteArrayOutputStream out = new ByteArrayOutputStream();
    	bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
    	return Base64.encode(out.toByteArray(), Base64.DEFAULT);
    	
    }
    
    /** 
     * 网络辅助结构
     */
    private static String mNetworkProxyHost = null;
    private static int mNetworkProxyPort = 0;
    /**
     * 检查网络，记录代理信息.需要在网络改变时调用
     * 该结构辅组{@link #getConnection(String)}进行网络连接状态判断
     * @param context
     */
    private static void checkNetWork(Context context){
    	ConnectivityManager connectivity = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
		if( connectivity != null ){
			NetworkInfo info = connectivity.getActiveNetworkInfo();
			if( info != null && info.getState() == NetworkInfo.State.CONNECTED){
				String extraInfo = info.getExtraInfo();
				if(extraInfo != null ){
					if(extraInfo.toUpperCase().contains("CMWAP")){
						mNetworkProxyHost = android.net.Proxy.getDefaultHost();
						mNetworkProxyPort = android.net.Proxy.getDefaultPort();
//						"10.0.0.172" 80
					}else{
						mNetworkProxyHost = null;
						mNetworkProxyPort = 0;
					}
				}
			}
		}
    }
    
    /**
     * 获取手机sdcard可用的容量
     */
    public static final long getSdCardAvailableSize(){
    	if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
    		StatFs sf = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
//    		Log.e(Constants.TAG, ((long)sf.getBlockSize()) * sf.getBlockCount() + "," + ((long)sf.getBlockSize() * sf.getAvailableBlocks()));
//    		Log.e(Constants.TAG, Utility.FormatFileSizeEx( ((long)sf.getBlockSize()) * sf.getBlockCount()) + "," + Utility.FormatFileSizeEx(((long)sf.getBlockSize()) * sf.getAvailableBlocks()));
    		return ((long)sf.getBlockSize()) * sf.getAvailableBlocks();
    	}
    	return 0;    	
    }
    /**
     * 获取手机内置存储可用的容量
     */
    public static final long getPhoneAvailableSize(){
    	StatFs sf = new StatFs(Environment.getDataDirectory().getAbsolutePath());
    	return ((long)sf.getBlockSize()) * sf.getAvailableBlocks();
    }
    
    /**
     * 重命名一个文件,并将文件权限改为777
     * @param srcFile
     * @param destFile
     */
    public static final boolean renameFile(File srcFile, File destFile){
    	try{
    		boolean bSuccess =  srcFile.renameTo(destFile);
    		if(bSuccess){
    			try{
    				String command = "chmod 777 " + destFile.getAbsolutePath();
        			Runtime runtime = Runtime.getRuntime();
        			runtime.exec(command);
    			}catch(Exception e){
    				if(DEBUG){
    					e.printStackTrace();
    				}
    			}
    		}
    		return bSuccess;
    	}catch(Exception e){
    		if(DEBUG){
    			e.printStackTrace();
    		}
    	}
    	return false;
    }
}
